<template>
  <div>
    <el-card class="sku-card">
      <el-form
        label-width="100px"
        ref="skuFormRef"
        :rules="skuFormRules"
        :model="skuFormData"
      >
        <el-form-item label="SPU 名称">
          {{ spu.spuName }}
        </el-form-item>
        <el-form-item label="SKU 名称" prop="skuName">
          <el-input
            placeholder="SKU 名称"
            v-model="skuFormData.skuName"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number
            v-model="skuFormData.price"
            class="sku-input-number"
            :min="0"
            :max="100000"
            controls-position="right"
            placeholder="请输入价格"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="重量(千克)" prop="weight">
          <el-input-number
            v-model="skuFormData.weight"
            class="sku-input-number"
            :min="0"
            :max="100000"
            controls-position="right"
            placeholder="请输入价格"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="规格描述" prop="skuDesc">
          <el-input
            :rows="4"
            type="textarea"
            placeholder="规格描述"
            v-model="skuFormData.skuDesc"
          ></el-input>
        </el-form-item>
        <el-form-item label="平台属性" prop="skuAttrValueList">
          <el-row :gutter="10" class="sku-wrap">
            <el-col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="4"
              v-for="(attr, index) in attrList"
              :key="attr.id"
            >
              <div class="sku-attr-wrap">
                <span class="sku-attr-name">{{ attr.attrName }}</span>
                <el-select v-model="skuFormData.skuAttrValueList[index]">
                  <el-option
                    v-for="attrValue in attr.attrValueList"
                    :key="attrValue.id"
                    :label="attrValue.valueName"
                    :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="销售属性" prop="skuSaleAttrValueList">
          <el-row :gutter="10" class="sku-wrap">
            <el-col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="4"
              v-for="(saleAttr, index) in spuSaleAttrList"
              :key="saleAttr.id"
            >
              <div class="sku-attr-wrap">
                <span class="sku-attr-name">{{ saleAttr.saleAttrName }}</span>
                <el-select v-model="skuFormData.skuSaleAttrValueList[index]">
                  <el-option
                    v-for="saleAttrVal in saleAttr.spuSaleAttrValueList"
                    :key="saleAttrVal.id"
                    :label="saleAttrVal.saleAttrValueName"
                    :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrVal.id}:${saleAttrVal.saleAttrValueName}`"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="图片列表" prop="skuImageList">
          <el-table
            :data="spuImageList"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column label="图片">
              <template v-slot="{ row }">
                <img :src="row.imgUrl" :alt="row.imgName" class="sku-img" />
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="imgName"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-tag type="success" v-if="row.isDefault == '1'">默认</el-tag>
                <el-button
                  type="primary"
                  v-else
                  size="small"
                  @click="setDefaultImg(row)"
                  >设置默认</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormData">保存</el-button>
          <el-button @click="ShowSpuList">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { AttrList } from "@/api/product/models/attrModel";
import type { AddSkuItem ,SkuImageItem} from "@/api/product/models/skuModel";
import type {
  SpuSaleAttrList,
  SpuImageList,
  AddSetSpuListItem,
} from "@/api/product/models/spuModel";
import { getAttrListApi } from "@/api/product/attr";

import { useCategoryStore } from "@/stores/category";
import { getSpuSaleAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import { addSkuApi } from "@/api/product/sku";

const CategoryStore = useCategoryStore();

//平台属性列表
const attrList = ref<AttrList>([]);
//销售属性列表
const spuSaleAttrList = ref<SpuSaleAttrList>([]);
//图片列表
const spuImageList = ref<SpuImageList>([]);

//接受props数据
const props = defineProps<{
  spu: AddSetSpuListItem; // 是ts类型，小写
}>();

//取消按钮的回调
const emits = defineEmits(["isShowAddSpu"]);
const ShowSpuList = () => {
  emits("isShowAddSpu", 1);
};

//获取平台属性列表
onMounted(async () => {
  const { category1Id, category2Id, category3Id } = CategoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});

//获取销售属性列表
onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(props.spu.id as number);
});

//获取图片列表
onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(props.spu.id as number);
});

//当点击表格图片复选框触发的回调
const handleSelectionChange = (val: SpuImageList) => {
  //val  点击的那个img数据
  skuFormData.skuImageList = val;
};

/*******************************收集表单数据功能**************************************/
//实例
const skuFormRef = ref<FormInstance>();
//表单数据
const skuFormData = reactive<AddSkuItem>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   attrId: 0,
    //   attrName: "string",
    //   valueId: 0,
    //   valueName: "string",
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    // },
  ],
  skuImageList: [
    // {
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    // },
  ],
  skuDefaultImg: "",
});

//自定义校验规则
const skuImageListRule = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback(new Error("请至少选择一张图片"));
  } else if (!skuFormData.skuDefaultImg) {
    callback(new Error("请至少选择一张默认图片"));
  } else {
    callback();
  }
};

//表单规则
const skuFormRules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU规则描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请选择SKU平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请选择SKU销售属性" }],
  skuImageList: [{ required: true, validator: skuImageListRule }],
});

/*******************************设置默认图片功能**************************************/
const setDefaultImg = (row:SkuImageItem) => {
  //排查思想,每次点击前先变为0,这样只会出现一个
  spuImageList.value.forEach((img) => ((img as any).isDefault = "0"));
  //显示默认
  row.isDefault = "1";
  //清除图片列表校验规则
  if (!skuFormData.skuDefaultImg) {
    skuFormRef.value?.clearValidate(["skuImageList"]);
  }
  //收集默认图片数据
  skuFormData.skuDefaultImg = row.imgUrl;
};

/*******************************提交表单功能**************************************/
const submitFormData = () => {
  //触发全部表单验证
  skuFormRef.value?.validate(async (valid) => {
    if (valid) {
      //发请求
      await addSkuApi({
        ...skuFormData,
        spuId: props.spu.id as number,
        category3Id: CategoryStore.category3Id as number,
        skuAttrValueList: skuFormData.skuAttrValueList
          .filter(Boolean)
          .map((attr) => {
            const [attrId, attrName, valueId, valueName] = (attr as any).split(":");
            return {
              //切割的是字符串,需要转换为number
              attrId: +attrId,
              attrName,
              valueId: +valueId,
              valueName,
            };
          }),
        skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
          .filter(Boolean)
          .map((attrValue) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = (attrValue as any).split(":");
            return {
              //切割的是字符串,需要转换为number
              saleAttrId: +saleAttrId,
              saleAttrName,
              saleAttrValueId: +saleAttrValueId,
              saleAttrValueName,
            };
          }),
      });
      ElMessage.success("添加SKU属性成功");
      //回到SPU界面
      ShowSpuList();
    }
  });
};
</script>

<style scoped lang="scss">
.sku-input-number,
.sku-wrap {
  width: 100%;
}
.sku-card {
  margin-top: 20px;
  &:deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
}
.sku-attr-name {
  margin-right: 10px;
  white-space: nowrap;
}

.sku-attr-wrap {
  margin-bottom: 10px;
  display: flex;
}
.sku-img {
  width: 100px;
}
</style>
